import {
  getDianxiaomiProductOrigin,
  getDianxiaomiUserInfo,
  getDianxiaomRegion2Id,
  getFreightTemplateId,
  getWarehouseId,
} from '@/api/product';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { ScrollArea } from '@/components/ui/scroll-area';
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import config from '@/config';
import { ShipmentLimitSecond } from '@/lib/dianxiaomi';
import { cn, generateRandomId, getDataUrl } from '@/lib/utils';
import { CategoryItem, useSettingsStore } from '@/store';
import { Search, SquareMinus, SquarePlus } from 'lucide-react';
import { useId } from 'react';
import { toast } from 'sonner';

const dxmStateMap = {
  draft: '采集箱',
  offline: '待发布',
  online: '在线产品',
};

type ShopIdItem = {
  shopId: string;
  shopName: string;
};

type CountryItem = {
  id: string;
  name: string;
};

type Region2Item = {
  id: string;
  name: string;
};

type FreightTemplateIdItem = {
  freightTemplateId: string;
  templateName: string;
};

type warehouseIdItem = {
  warehouseId: string;
  warehouseName: string;
};
export default function BaseDocSetting({
  className,
  ...props
}: {
  className: string;
} & React.HTMLAttributes<HTMLDivElement>) {
  const pushSettings = useSettingsStore((state) => state.pushSettings);
  const dispatch = useSettingsStore((state) => state.dispatch);
  const [shopIds, setShopIds] = useState<ShopIdItem[]>([]);
  const [productOrigins, setProductOrigins] = useState<CountryItem[]>([]);
  const [region2s, setRegion2s] = useState<Region2Item[]>([]);
  const [freightTemplateIdList, setFreightTemplateIdList] = useState<FreightTemplateIdItem[]>([]);
  const [warehouseIdList, setWarehouseIdList] = useState<warehouseIdItem[]>([]);
  const [categoryOptionFilterString, setCategoryOptionFilterString] = useState('');
  const id = useId();
  // console.log(baseSettings);

  useEffect(() => {
    async function getShopIds() {
      const useInfo = await getDianxiaomiUserInfo();
      const shopMap = useInfo.data.shopMap;
      const items: ShopIdItem[] = [];
      Object.keys(shopMap).map((key) => {
        if (key !== '0') {
          items.push({
            shopId: shopMap[key].id.toString(),
            shopName: shopMap[key].name,
          });
        }
      });
      setShopIds(items);
    }
    getShopIds();
  }, []);

  useEffect(() => {
    async function getProductOrigins() {
      const countriesMap = await getDianxiaomiProductOrigin();
      setProductOrigins(
        Object.keys(countriesMap).map((key) => {
          return { id: key, name: countriesMap[key] };
        }),
      );
    }
    getProductOrigins();
  }, []);

  // 获取运费模版
  useEffect(() => {
    async function getFreightTemplateIdList() {
      if (!pushSettings.shopId) {
        toast.error('请先选择店铺');
      }
      const getFreightTemplateIdResult = await getFreightTemplateId(pushSettings.shopId);
      if (getFreightTemplateIdResult.code === 0) {
        setFreightTemplateIdList(
          getFreightTemplateIdResult.data.map((item) => {
            return {
              freightTemplateId: item.freightTemplateId,
              templateName: item.templateName,
            };
          }),
        );
      } else {
        console.log('获取运费模版失败', getFreightTemplateIdResult.msg);
        toast.error(`获取运费模版失败: ${getFreightTemplateIdResult.msg}`);
      }
    }
    getFreightTemplateIdList();
  }, [pushSettings.shopId]);

  // 获取云仓列表
  useEffect(() => {
    async function getWarehouseIdList() {
      if (!pushSettings.shopId) {
        toast.error('请先选择店铺');
      }
      const getWarehouseIdResult = await getWarehouseId(pushSettings.shopId);
      // console.log(getWarehouseIdResult);
      if (getWarehouseIdResult.code === 0) {
        setWarehouseIdList(
          getWarehouseIdResult.data[0].warehouseList.map((item) => {
            return {
              warehouseId: item.id,
              warehouseName: item.name,
            };
          }),
        );
      } else {
        console.log('获取云仓列表失败', getWarehouseIdResult.msg);
        toast.error(`获取云仓列表失败: ${getWarehouseIdResult.msg}`);
      }
    }
    getWarehouseIdList();
  }, [pushSettings.shopId]);

  useEffect(() => {
    async function getRegion2Ids() {
      const regoin2IdsMap = (await getDianxiaomRegion2Id()).CN;
      setRegion2s(
        Object.keys(regoin2IdsMap).map((key) => {
          return { id: key, name: regoin2IdsMap[key] };
        }),
      );
    }
    getRegion2Ids();
  }, []);

  // 处理配置分类的属性提前
  useEffect(() => {
    function handlerAttributesExtract(event: Event) {
      const customEvent = event as CustomEvent<
        CategoryItem & {
          prefine: boolean;
          isAdd: boolean;
        }
      >;
      const { detail } = customEvent;
      // console.log('handlerAttributesExtract', detail);
      if (detail) {
        if (detail.prefine) {
          if (detail.isAdd) {
            dispatch({
              type: 'update',
              update(draftState) {
                draftState.pushSettings.categoryOptionList.push({
                  id: generateRandomId(),
                  categoryName: detail.categoryName,
                  attributes: detail.attributes,
                  categoryId: detail.categoryId,
                });
              },
            });
            return;
          }
          dispatch({
            type: 'update',
            update(draftState) {
              draftState.pushSettings.categoryOptionList =
                draftState.pushSettings.categoryOptionList.map((item) => {
                  if (item.id === detail.id) {
                    item.attributes = detail.attributes;
                    item.categoryId = detail.categoryId;
                    item.categoryName = detail.categoryName;
                  }
                  return item;
                });
            },
          });
        } else {
          dispatch({
            type: 'update',
            update(draftState) {
              draftState.pushSettings.category.attributes = detail.attributes;
              draftState.pushSettings.category.categoryId = detail.categoryId;
              draftState.pushSettings.category.categoryName = detail.categoryName;
            },
          });
        }
      }
    }
    window.addEventListener('attributes-extract', handlerAttributesExtract);

    return () => {
      window.removeEventListener('attributes-extract', handlerAttributesExtract);
    };
  }, []);

  return (
    <div {...props} className={cn(className, 'flex flex-col')}>
      <div className="grow relative flex flex-col">
        <ScrollArea className="border rounded-sm grow h-full w-full p-2 pt-2 overflow-auto [&_[data-radix-scroll-area-viewport]]:absolute [&_[data-radix-scroll-area-viewport]]:!w-auto [&_[data-radix-scroll-area-viewport]]:right-2 [&_[data-radix-scroll-area-viewport]]:left-2">
          <div className="flex px-3 gap-2 items-center py-4 bd-bottom-gray">
            <Label className="whitespace-nowrap mb-0" htmlFor={id + '-shop-id'}>
              店铺账号:
            </Label>
            <Select
              value={pushSettings.shopId}
              onValueChange={(value) => {
                dispatch({
                  type: 'update',
                  update(draftState) {
                    draftState.pushSettings.shopId = value;
                  },
                });
              }}
            >
              <SelectTrigger id={id + '-shop-id'} className="w-[180px]">
                <SelectValue placeholder="---- 请选择店铺 ----" />
              </SelectTrigger>
              <SelectContent
                style={{
                  zIndex: config.SelectZindex,
                }}
              >
                <SelectGroup>
                  {shopIds.map(({ shopId, shopName }) => {
                    return (
                      <SelectItem key={shopId} value={shopId}>
                        {shopName}
                      </SelectItem>
                    );
                  })}
                </SelectGroup>
              </SelectContent>
            </Select>
          </div>
          {/* <div className="flex px-3 gap-2 items-center py-4 bd-bottom-gray">
            <Label className="whitespace-nowrap mb-0">发布类型:</Label>
            <RadioGroup
              className="flex items-center"
              value={pushSettings.dxmState}
              onValueChange={(value) => {
                dispatch({
                  type: 'update',
                  update(draftState) {
                    draftState.pushSettings.dxmState = value as DxmState;
                  },
                });
              }}
            >
              {Object.values(DxmState).map((value) => {
                return (
                  <div className="inline-flex items-center space-x-2" key={value}>
                    <RadioGroupItem value={value} id={id + '-dxm-state-' + value} />
                    <Label className="mb-0" htmlFor={id + '-dxm-state-' + value}>
                      {dxmStateMap[value]}
                    </Label>
                  </div>
                );
              })}
            </RadioGroup>
          </div> */}
          <div className="flex px-3 gap-2 items-center py-4">
            <Label className="whitespace-nowrap mb-0" htmlFor={id + '-price-multiplying-factor'}>
              价格浮动倍数:
            </Label>
            <Input
              value={pushSettings.priceMultiplyingFactor}
              type="number"
              step={0.1}
              onChange={(event) => {
                dispatch({
                  type: 'update',
                  update(draftState) {
                    draftState.pushSettings.priceMultiplyingFactor = +event.target.value;
                  },
                });
              }}
              id={id + '-price-multiplying-factor'}
              className="h-10 w-auto rounded-md border border-input px-3 py-2"
            />
          </div>
          <div className="flex items-center px-3 gap-2">
            <div className="inline-flex gap-2 items-center py-4 bd-bottom-gray">
              <Label
                className="whitespace-nowrap"
                htmlFor={id + '-category-' + pushSettings.category.id}
              >
                指定产品分类:
              </Label>
              <Input
                value={pushSettings.category.categoryName}
                onChange={(event) => {
                  dispatch({
                    type: 'update',
                    update(draftState) {
                      // 更新对应的 name 属性
                      draftState.pushSettings.category.categoryName = event.target.value;
                    },
                  });
                }}
                id={id + '-category-' + pushSettings.category.id}
                className="h-10 w-auto rounded-md border border-input px-3 py-2 mr-auto"
              />
            </div>
            <div className="inline-flex px-3 gap-2 items-center py-4 bd-bottom-gray">
              <Label
                className="whitespace-nowrap"
                htmlFor={id + '-attributes-' + pushSettings.category.id}
              >
                指定产品属性:
              </Label>
              <Input
                value={pushSettings.category.attributes}
                onChange={(event) => {
                  dispatch({
                    type: 'update',
                    update(draftState) {
                      // 更新对应的 name 属性
                      draftState.pushSettings.category.attributes = event.target.value;
                    },
                  });
                }}
                id={id + '-attributes-' + pushSettings.category.id}
                className="h-10 w-auto rounded-md border border-input px-3 py-2 mr-auto"
              />
            </div>
            <Button
              size={'sm'}
              className="hover:bg-[#337AB7] bg-[#428BCA] mr-3"
              onClick={() => {
                window.open(
                  `https://www.dianxiaomi.com/web/popTemu/quoteEdit?id=114622919199237918&category=${pushSettings.category.id}`,
                );
              }}
            >
              选择分类
            </Button>
          </div>
          <div className="flex items-center">
            <div className="flex px-3 gap-2 items-center pb-2">
              <Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
              <Input
                placeholder="预配置产品分类名称"
                value={categoryOptionFilterString}
                onChange={(event) => {
                  setCategoryOptionFilterString(event.target.value);
                }}
                className={cn(
                  'flex max-w-[200px] h-10 bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50 rounded-md border border-input',
                  className,
                )}
                {...props}
              />
            </div>
            <div className="flex px-3 gap-2 py-4 items-center">
              <Checkbox
                checked={pushSettings.isUseAiCategory}
                onCheckedChange={(state) => {
                  dispatch({
                    type: 'update',
                    update(draftState) {
                      draftState.pushSettings.isUseAiCategory = state ? true : false;
                    },
                  });
                }}
                id={id + '-is-use-ai-category'}
                className="rounded-[2px]"
              />
              <Label className="whitespace-nowrap mb-0 ml-3" htmlFor={id + '-is-use-ai-category'}>
                是否使用 ai 进行产品分类,而不使用指定产品分类
              </Label>
              <Button
                size="sm"
                className="ml-6 hover:bg-[#337AB7] bg-[#428BCA]"
                onClick={() => {
                  const uniqueByCategoryName = (list: CategoryItem[]) => {
                    const map = new Map<string, CategoryItem>();
                    // 反向遍历确保后出现的覆盖先出现的
                    for (let i = list.length - 1; i >= 0; i--) {
                      const item = list[i];
                      if (!map.has(item.categoryName)) {
                        map.set(item.categoryName, item);
                      }
                    }
                    return Array.from(map.values()).reverse(); // 恢复原始顺序
                  };
                  dispatch({
                    type: 'update',
                    update(draftState) {
                      draftState.pushSettings.categoryOptionList = uniqueByCategoryName(
                        pushSettings.categoryOptionList,
                      );
                    },
                  });
                }}
              >
                去重({pushSettings.categoryOptionList.length})
              </Button>
            </div>
          </div>
          <div className="border border-input rounded-lg py-3 px-3 relative mt-3 flex items-center flex-wrap">
            <span className="absolute left-2 top-0 translate-y-[-50%] text-base bg-white">
              预配置产品分类
            </span>
            <div className="max-h-[300px] overflow-auto w-full">
              {pushSettings.categoryOptionList
                .filter((categoryOption) => {
                  return categoryOption.categoryName.includes(categoryOptionFilterString);
                })
                .map((category: CategoryItem, index) => {
                  return (
                    <div key={category.id} className="flex items-center">
                      <div className="inline-flex px-3 gap-2 items-center py-4 bd-bottom-gray">
                        <Label
                          className="whitespace-nowrap"
                          htmlFor={id + '-category-' + category.id}
                        >
                          产品分类:
                        </Label>
                        <Input
                          value={category.categoryName}
                          onChange={(event) => {
                            dispatch({
                              type: 'update',
                              update(draftState) {
                                draftState.pushSettings.categoryOptionList[index].categoryName =
                                  event.target.value;
                              },
                            });
                          }}
                          id={id + '-category-' + category.id}
                          className="h-10 w-auto rounded-md border border-input px-3 py-2 mr-auto"
                        />
                      </div>
                      <div
                        className="inline-flex px-3 gap-2 items-center py-4 bd-bottom-gray"
                        key={category.id}
                      >
                        <Label
                          className="whitespace-nowrap"
                          htmlFor={id + '-attributes-' + category.id}
                        >
                          产品属性:
                        </Label>
                        <Input
                          value={category.attributes}
                          onChange={(event) => {
                            dispatch({
                              type: 'update',
                              update(draftState) {
                                draftState.pushSettings.categoryOptionList[index].attributes =
                                  event.target.value;
                              },
                            });
                          }}
                          id={id + '-attributes-' + category.id}
                          className="h-10 w-auto rounded-md border border-input px-3 py-2 mr-auto"
                        />
                      </div>
                      <Button
                        size={'sm'}
                        className="hover:bg-[#337AB7] bg-[#428BCA] mr-3"
                        onClick={() => {
                          window.open(
                            `https://www.dianxiaomi.com/web/popTemu/quoteEdit?id=114622919199237918&category=${category.id}&prefine=1`,
                          );
                        }}
                      >
                        选择分类
                      </Button>
                      <Button
                        size={'sm'}
                        className="hover:bg-[#337AB7] bg-[#428BCA] mr-3"
                        onClick={() => {
                          dispatch({
                            type: 'update',
                            update(draftState) {
                              draftState.pushSettings.category = {
                                id: category.id,
                                categoryName: category.categoryName,
                                attributes: category.attributes,
                                categoryId: category.categoryId,
                              };
                            },
                          });
                        }}
                      >
                        指定分类
                      </Button>
                      <div
                        className="inline-flex items-center cursor-pointer mr-3"
                        onClick={() => {
                          dispatch({
                            type: 'update',
                            update(draftState) {
                              draftState.pushSettings.categoryOptionList.splice(index + 1, 0, {
                                id: generateRandomId(),
                                categoryName: '',
                                attributes: '',
                                categoryId: '',
                              });
                            },
                          });
                        }}
                      >
                        <SquarePlus className="text-primary"></SquarePlus>
                      </div>
                      <div
                        className="inline-flex items-center cursor-pointer"
                        onClick={() => {
                          if (pushSettings.categoryOptionList.length === 1) {
                            toast.error('最后一个分类不能被移除');
                            return;
                          }
                          dispatch({
                            type: 'update',
                            update(draftState) {
                              // 更新对应的 name 属性
                              draftState.pushSettings.categoryOptionList =
                                draftState.pushSettings.categoryOptionList.filter(
                                  (item) => item.id !== category.id,
                                );
                            },
                          });
                        }}
                      >
                        <SquareMinus className="text-destructive"></SquareMinus>
                      </div>
                    </div>
                  );
                })}
            </div>
          </div>
          <div className="flex px-3 gap-2 items-center py-4 bd-bottom-gray">
            <Label className="whitespace-nowrap mb-0">产地:</Label>
            <Select
              value={pushSettings.productOrigin}
              onValueChange={(value) => {
                dispatch({
                  type: 'update',
                  update(draftState) {
                    draftState.pushSettings.productOrigin = value;
                  },
                });
              }}
            >
              <SelectTrigger className="w-[180px] mr-3">
                <SelectValue placeholder="-- 请选择产地 --" />
              </SelectTrigger>
              <SelectContent
                style={{
                  zIndex: config.SelectZindex,
                }}
              >
                <SelectGroup>
                  {productOrigins.map(({ id, name }) => {
                    return (
                      <SelectItem key={id} value={id}>
                        {name}
                      </SelectItem>
                    );
                  })}
                </SelectGroup>
              </SelectContent>
            </Select>
            {pushSettings.productOrigin === 'CN' && (
              <Select
                value={pushSettings.region2Id}
                onValueChange={(value) => {
                  dispatch({
                    type: 'update',
                    update(draftState) {
                      draftState.pushSettings.region2Id = value;
                    },
                  });
                }}
              >
                <SelectTrigger className="w-[180px]">
                  <SelectValue placeholder="-- 请选择省份 --" />
                </SelectTrigger>
                <SelectContent
                  style={{
                    zIndex: config.SelectZindex,
                  }}
                >
                  <SelectGroup>
                    {region2s.map(({ id, name }) => {
                      return (
                        <SelectItem key={id} value={id}>
                          {name}
                        </SelectItem>
                      );
                    })}
                  </SelectGroup>
                </SelectContent>
              </Select>
            )}
          </div>
          <div className="flex px-3 gap-2 items-center py-4 bd-bottom-gray">
            <Label className="whitespace-nowrap mb-0">承诺发货时效:</Label>
            <RadioGroup
              className="flex items-center"
              value={pushSettings.shipmentLimitSecond}
              onValueChange={(value) => {
                dispatch({
                  type: 'update',
                  update(draftState) {
                    draftState.pushSettings.shipmentLimitSecond = value as ShipmentLimitSecond;
                  },
                });
              }}
            >
              {Object.keys(ShipmentLimitSecond).map((key) => {
                return (
                  <div className="inline-flex items-center space-x-2" key={key}>
                    <RadioGroupItem
                      value={ShipmentLimitSecond[key as keyof typeof ShipmentLimitSecond]}
                      id={id + '-' + key}
                    />
                    <Label className="mb-0" htmlFor={id + '-' + key}>
                      {key}
                    </Label>
                  </div>
                );
              })}
            </RadioGroup>
          </div>
          <div className="flex px-3 gap-2 items-center py-4 bd-bottom-gray">
            <Label className="whitespace-nowrap mb-0">运费模版:</Label>
            <Select
              value={pushSettings.freightTemplateId}
              onValueChange={(value) => {
                dispatch({
                  type: 'update',
                  update(draftState) {
                    draftState.pushSettings.freightTemplateId = value;
                  },
                });
              }}
            >
              <SelectTrigger className="w-[180px]">
                <SelectValue placeholder="-- 请选择运费模版 --" />
              </SelectTrigger>
              <SelectContent
                style={{
                  zIndex: config.SelectZindex,
                }}
              >
                <SelectGroup>
                  {freightTemplateIdList.map(({ freightTemplateId, templateName }) => {
                    return (
                      <SelectItem key={freightTemplateId} value={freightTemplateId}>
                        {templateName}
                      </SelectItem>
                    );
                  })}
                </SelectGroup>
              </SelectContent>
            </Select>

            <Label className="whitespace-nowrap mb-0 ml-3">选择云仓:</Label>
            <Select
              value={pushSettings.warehouseId}
              onValueChange={(value) => {
                dispatch({
                  type: 'update',
                  update(draftState) {
                    draftState.pushSettings.warehouseId = value;
                  },
                });
              }}
            >
              <SelectTrigger className="w-[180px]">
                <SelectValue placeholder="-- 请选择云仓 --" />
              </SelectTrigger>
              <SelectContent
                style={{
                  zIndex: config.SelectZindex,
                }}
              >
                <SelectGroup>
                  {warehouseIdList.map(({ warehouseId, warehouseName }) => {
                    return (
                      <SelectItem key={warehouseId} value={warehouseId}>
                        {warehouseName}
                      </SelectItem>
                    );
                  })}
                </SelectGroup>
              </SelectContent>
            </Select>
          </div>

          <div className="flex px-3 gap-2 items-center py-2">
            <Button
              onClick={async () => {
                const fileHandle = await window.showOpenFilePicker({
                  multiple: false,
                });
                const file = await fileHandle[0].getFile();
                const dataUrl = await getDataUrl(file);
                // console.log(violateList);
                dispatch({
                  type: 'update',
                  update(draftState) {
                    draftState.pushSettings.commonProductInstructions = dataUrl;
                  },
                });
              }}
              size={'sm'}
              className="hover:bg-[#337AB7] bg-[#428BCA]"
            >
              添加通用的产品说明书
              {pushSettings.commonProductInstructions
                ? `(已配置通用的产品说明书)`
                : `(未配置通用的产品说明书)`}
            </Button>
          </div>

          <div className="flex px-3 gap-2 py-4 bd-bottom-gray items-center">
            <Checkbox
              checked={pushSettings.isUploadToImageSpace}
              onCheckedChange={(state) => {
                dispatch({
                  type: 'update',
                  update(draftState) {
                    draftState.pushSettings.isUploadToImageSpace = state ? true : false;
                  },
                });
              }}
              id={id + '-is-upload-to-image-space'}
              className="rounded-[2px]"
            />
            <Label className="whitespace-nowrap mb-0" htmlFor={id + '-is-upload-to-image-space'}>
              上传图片时是否加入到图片空间中
            </Label>
          </div>
        </ScrollArea>
      </div>
    </div>
  );
}
